package com.example.unique.ui.task

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.NumberPicker
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.example.unique.MapSelection2Activity
import com.example.unique.R
import com.example.unique.database.DatabaseHelper
import com.example.unique.database.DatabaseJob
import com.example.unique.database.DatabaseTaskCompletion
import com.example.unique.databinding.FragmentTaskBinding
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.WriterException
import com.google.zxing.qrcode.QRCodeWriter
import java.util.Calendar
import java.util.Hashtable
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


class TaskFragment: Fragment() {

    private var _binding: FragmentTaskBinding? = null
    private val binding get() = _binding!!
    private lateinit var timeText: TextView
    private lateinit var deadlineText: TextView
    private lateinit var qrCodeImage: ImageView
    private lateinit var publishTime: Calendar
    private var deadlineTime: Calendar? = null
    private val handler = Handler(Looper.getMainLooper())
    private var isDeadlinePassed = false
    private lateinit var jobDataBase:DatabaseJob
    private lateinit var taskCompletion: DatabaseTaskCompletion
    private lateinit var userDatabaseHelper: DatabaseHelper
    private lateinit var title:EditText
    private lateinit var address:String
    private var radius:Double=0.0
    private lateinit var club: String
    private lateinit var locationTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        club = activity?.intent?.getStringExtra("club").toString()
        jobDataBase=DatabaseJob.getInstance(requireContext())
        userDatabaseHelper=DatabaseHelper(requireContext())
        taskCompletion=DatabaseTaskCompletion.getInstance(requireContext())
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentTaskBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        title = view.findViewById(R.id.job_title)
        val setStartTimeButton = view.findViewById<ImageButton>(R.id.setTime)
        val setEndTimeButton = view.findViewById<ImageButton>(R.id.setDeadline)
        val publishButton: Button = view.findViewById(R.id.publish)
        qrCodeImage = view.findViewById(R.id.qrCodeImage)
        timeText = view.findViewById(R.id.job_time)
        deadlineText = view.findViewById(R.id.deadline_text)
        //1
        locationTextView = view.findViewById(R.id.location_text)
        val setLocationButton: Button = view.findViewById(R.id.setLocationButton)
        setLocationButton.setOnClickListener {
            val intent=Intent(requireContext(),MapSelection2Activity::class.java)
            startActivityForResult(intent, 1001)
        }
        setStartTimeButton.setOnClickListener { showDateTimePickerDialog() }

        setEndTimeButton.setOnClickListener { showDeadlinePickerDialog(deadlineText) }

        publishButton.setOnClickListener {
            val input = title.text.toString()
            val start=timeText.text
            val end=deadlineText.text
            if (input.isEmpty()) {
                showAlert("请设置标题")
                return@setOnClickListener
            }
            if (isTaskNameDuplicate(input)) {
                showAlert("任务标题已存在，请更换！")
                return@setOnClickListener
            }
            if (start.isEmpty()) {
                showAlert("请设置发布时间")
                return@setOnClickListener
            }
            if (end.isEmpty()) {
                showAlert("请设置截止时间")
                return@setOnClickListener
            }
            if(address==null || radius==null){
                showAlert("请设置打卡地点和范围")
                return@setOnClickListener
            }
            // 生成二维码
            val bitMap = CreateUtil.createQRCode(input, 280, 280)
            qrCodeImage.setImageBitmap(bitMap)
            // 保存二维码到文件系统并获取路径
            val qrCodeFilePath = "${context?.filesDir}/qrcodes/${System.currentTimeMillis()}.png"
            val savedPath =CreateUtil.saveBitmapToFile(bitMap, qrCodeFilePath)

            showAlert("发布成功！")
            if (savedPath != null) {
                taskCompletion.insertTaskCompletionForClub(club,input,userDatabaseHelper)
                jobDataBase.insertJob(club,start.toString(),end.toString(),address,radius,0, input,savedPath)
                startPublishTimer()
            } else {
                Log.e("QRCode", "二维码保存失败")
                showAlert("发布任务失败，请重试！")
            }
        }



        view.findViewById<Button>(R.id.cancel).setOnClickListener {
            qrCodeImage.setImageBitmap(null)  // 清除二维码

        }
        startDeadlineChecker()
    }

    object CreateUtil {
        fun createQRCode(codestring: String?, width: Int, height: Int): Bitmap? {
            try {
                if (TextUtils.isEmpty(codestring) || width <= 0 || height <= 0) return null
                val hashtable = Hashtable<EncodeHintType, String?>()
                hashtable[EncodeHintType.CHARACTER_SET] = "utf-8"
                hashtable[EncodeHintType.ERROR_CORRECTION] = "H"
                hashtable[EncodeHintType.MARGIN] = "2"
                val bitMatrix = QRCodeWriter().encode(
                    codestring,
                    BarcodeFormat.QR_CODE,
                    width,
                    height,
                    hashtable
                )
                val pixel = IntArray(width * width)
                for (h in 0 until height) {
                    for (w in 0 until width) {
                        pixel[h * width + w] = if (bitMatrix[w, h]) Color.BLACK else Color.WHITE
                    }
                }
                val qrcodemap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
                qrcodemap.setPixels(pixel, 0, width, 0, 0, width, height)
                return qrcodemap
            } catch (e: WriterException) {
                return null
            }
        }
        fun saveBitmapToFile(bitmap: Bitmap?, filePath: String): String? {
            return try {
                val file = File(filePath)
                if (!file.parentFile.exists()) {
                    file.parentFile.mkdirs()
                }
                FileOutputStream(file).use { fos ->
                    bitmap?.compress(Bitmap.CompressFormat.PNG, 100, fos)
                }
                file.absolutePath // 返回文件路径
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }



    }

    fun isTaskNameDuplicate(taskName: String): Boolean {
        val cursor = jobDataBase.readableDatabase.rawQuery(
            "SELECT COUNT(*) FROM Job WHERE taskName = ?",
            arrayOf(taskName)
        )
        cursor.moveToFirst()
        val count = cursor.getInt(0)
        cursor.close()
        return count > 0
    }

    private fun showDateTimePickerDialog() {
        val bottomSheetDialog = BottomSheetDialog(requireContext())
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.bottom_sheet_time_picker, null)
        bottomSheetDialog.setContentView(view)
        val datePicker = view.findViewById<NumberPicker>(R.id.np_date)
        val hourPicker = view.findViewById<NumberPicker>(R.id.np_hour)
        val minutePicker = view.findViewById<NumberPicker>(R.id.np_minute)
        val confirmButton = view.findViewById<TextView>(R.id.tv_confirm)

        val dates = arrayOf("今天", "明天", "后天")
        datePicker?.apply {
            minValue = 0
            maxValue = dates.size - 1
            displayedValues = dates
        }

        val calendar = Calendar.getInstance()
        hourPicker?.apply {
            minValue = 0
            maxValue = 23
            value = calendar.get(Calendar.HOUR_OF_DAY)
            setFormatter { i -> String.format("%02d点", i) }
        }

        minutePicker?.apply {
            minValue = 0
            maxValue = 59
            value = calendar.get(Calendar.MINUTE)
            setFormatter { i -> String.format("%02d分", i) }
        }

        confirmButton?.setOnClickListener {
            val selectedDate = dates[datePicker.value]
            val selectedHour = String.format("%02d", hourPicker.value)
            val selectedMinute = String.format("%02d", minutePicker.value)
            timeText.text = "$selectedDate $selectedHour:$selectedMinute"

            publishTime = Calendar.getInstance().apply {
                add(Calendar.DAY_OF_YEAR, datePicker.value)
                set(Calendar.HOUR_OF_DAY, hourPicker.value)
                set(Calendar.MINUTE, minutePicker.value)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }
            bottomSheetDialog.dismiss()
        }
        bottomSheetDialog.show()
    }

    private fun showDeadlinePickerDialog(textView: TextView) {
        val bottomSheetDialog = BottomSheetDialog(requireContext())
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.bottom_sheet_time_picker, null)
        bottomSheetDialog.setContentView(view)
        val datePicker = view.findViewById<NumberPicker>(R.id.np_date)
        val hourPicker = view.findViewById<NumberPicker>(R.id.np_hour)
        val minutePicker = view.findViewById<NumberPicker>(R.id.np_minute)
        val confirmButton = view.findViewById<TextView>(R.id.tv_confirm)

        val dates = arrayOf("今天", "明天", "后天")
        datePicker?.apply {
            minValue = 0
            maxValue = dates.size - 1
            displayedValues = dates
        }

        hourPicker?.apply {
            minValue = 0
            maxValue = 23
            setFormatter { i -> String.format("%02d点", i) }
        }

        minutePicker?.apply {
            minValue = 0
            maxValue = 59
            setFormatter { i -> String.format("%02d分", i) }
        }

        confirmButton?.setOnClickListener {
            val selectedDate = dates[datePicker.value]
            val selectedHour = String.format("%02d", hourPicker.value)
            val selectedMinute = String.format("%02d", minutePicker.value)
            val calendar = Calendar.getInstance().apply {
                add(Calendar.DAY_OF_YEAR, datePicker.value)
                set(Calendar.HOUR_OF_DAY, hourPicker.value)
                set(Calendar.MINUTE, minutePicker.value)
            }
            if (calendar.before(publishTime)) {
                showAlert("截止时间不得早于发布时间")
                return@setOnClickListener
            }
            deadlineTime = calendar
            textView.text = "$selectedDate $selectedHour:$selectedMinute"
            bottomSheetDialog.dismiss()
        }
        bottomSheetDialog.show()
    }

    private fun startPublishTimer() {
        val delay = publishTime.timeInMillis - Calendar.getInstance().timeInMillis
        handler.postDelayed({
            showAlert("任务已成功发送")
        }, delay)
        jobDataBase.updateStatus(club,title.toString(),1)
    }
    private fun startDeadlineChecker() {
        val deadlineCheckerRunnable = object : Runnable {
            override fun run() {
                if (isDeadlinePassed) return
                val currentTime = Calendar.getInstance()
                if (deadlineTime != null && currentTime.after(deadlineTime)) {
                    jobDataBase.updateStatus(club,title.toString(),3)
                    handler.post {
                        showAlert("任务已截止！")
                    }
                    isDeadlinePassed = true
                    deadlineTime = null
                }
                if (!isDeadlinePassed) {
                    handler.postDelayed(this, 1000)
                }
            }
        }
        handler.post(deadlineCheckerRunnable)
    }

    private fun showAlert(message: String) {
        AlertDialog.Builder(requireContext())
            .setTitle("提示")
            .setMessage(message)
            .setPositiveButton("确定") { dialog, _ -> dialog.dismiss() }
            .show()
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1001 && resultCode == 666) {
            address = data?.getStringExtra("address").toString()
            radius = data?.getDoubleExtra("radius", 0.0)!!
            locationTextView.text = "任务位置：$address，范围：${radius}米"
        }
    }

}